﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using HalalCheck.DataModels;
using HalalCheck.Resources;
using SpotOffer.Resource;
using Xamarin.Forms;
using XLabs.Caching;
using XLabs.Ioc;

namespace HalalCheck.ViewModels
{
    public class ChecknShareViewModel : BaseViewModel
    {
        private List<HalalItem> _halalList;
        public List<HalalItem> HalalList
        {
			get
			{
				if (_halalList != null) {
					return _halalList.Where (
						deal => deal.Name.Trim ().ToLower ().Contains (_search.Trim ().ToLower ())
						|| deal.Id.Trim ().ToLower ().Contains (_search.Trim ().ToLower ())).ToList ();
				} else {
					return null;
				}

			}
            set
            {
                if (value != null)
                {
                    _halalList = value;

                }
                NotifyPropertyChanged();
            }
        }
        public string ProductName { get; set; }
        public string Status { get; set; }
        public string Description { get; set; }
        public string Reason { get; set; }
        private string _search = "";
        public string Search
        {
            get { return _search; }
            set
            {
                if (value != null)
                {
                    _search = value;
                    NotifyPropertyChanged("HalalList");
                }
            }
        }

        public Color HalalStatusColor
        {
            get
            {
                var status = 0;
                foreach (var item in HalalList)
                {
                    if (item.Checked & item.Halal > status)
                    {
                        status = item.Halal;
                    }
                }
                return GetHalalColor(status);
            }
        }
        public ICommand ShareCommand
        {
            get
            {
                return new Command(async (s) =>
                {
                    var shareString = HalalStrings.Product + ": " + ProductName + "\n" + HalalStrings.Status + ": " + CalculateStatus();
                    Debug.WriteLine(shareString);
                });
            }
        }
        public ChecknShareViewModel()
        {
            GetHalalListFromTxt();
        }

        private string CalculateStatus()
        {
            int status = 0;
            foreach (var item in HalalList)
            {
                if (item.Checked & item.Halal > status)
                {
                    status = item.Halal;
                }
            }
            return HalalItem.GetHalalStatusString(status);
        }

        public Color GetHalalColor(int status)
        {
            switch (status)
            {
                case 0:
                    return AppColors.Green;
                case 1:
                    return AppColors.DarkGrey;
                case 2:
                    return AppColors.Red;
                default:
                    return AppColors.Green;
            }
        }

        private async void GetHalalListFromTxt()
        {
            var halalListKey = "HalalCheck.Resources.halaldb" +
                               CultureInfo.CurrentCulture
                                   .TwoLetterISOLanguageName.ToString() + ".txt";
            HalalList = Resolver.Resolve<ISimpleCache>().Get<List<HalalItem>>(halalListKey);
            if (HalalList == null)
            {
                #region How to load a text file embedded resource

                var assembly = typeof(HalalListViewModel).GetTypeInfo().Assembly;
                Stream stream =
                    assembly.GetManifestResourceStream(halalListKey);
                if (stream == null)
                {
                    stream = assembly.GetManifestResourceStream("HalalCheck.Resources.halaldb.txt");
                }

                using (var reader = new StreamReader(stream, Encoding.UTF8, true))
                {
                    var temp = new List<HalalItem>();

                    while (!reader.EndOfStream)
                    {

                        var line = await reader.ReadLineAsync();

                        var values = line.Split('_');

                        HalalItem item = new HalalItem
                        {
                            Halal = Convert.ToInt32(values[1]),
                            Id = values[0],
                            Name = UpperFirst(values[2]),
                            Description = UpperFirst(values[3]),
                        };
                        temp.Add(item);
                    }
                    HalalList = temp;
                    Resolver.Resolve<ISimpleCache>().Set(halalListKey, HalalList);
                }
                #endregion
            }
        }
        static string UpperFirst(string s)
        {
            // Check for empty string.
            if (string.IsNullOrEmpty(s))
            {
                return string.Empty;
            }
            // Return char and concat substring.
            return char.ToUpper(s[0]) + s.Substring(1);
        }
    }
}
